<template>
    <div v-if="article">
        <Article :article="article" :isShort="false"></Article>
        <el-button
            @click="commentDrawer = !commentDrawer"
            class="drawer-opener"
            v-if="token!=undefined"
        ><unicon name="comment-edit" fill="cyan"></unicon> 留言</el-button>
        <el-drawer v-model="commentDrawer" :destroy-on-close="true">
            <el-form :model="form" ref="formRef" :rules="rules" style="margin:0 1em;">
                <el-form-item prop="owner">
                    <el-input
                        v-model.trim="form.owner"
                        placeholder="称呼"
                        :maxlength="20"
                        show-word-limit
                    ></el-input>
                </el-form-item>
                <el-form-item prop="content">
                    <el-input
                        v-model="form.content"
                        :maxlength="100"
                        show-word-limit
                        type="textarea"
                        :autosize="{ minRows: 3, maxRows: 10 }"
                        :placeholder="commentPlaceholder"
                    ></el-input>
                </el-form-item>
                <el-form-item style="text-align:right">
                    <el-button @click="submitComment" type="primary" size="mini">提交</el-button>
                    <el-button size="mini" @click="resetForm">清空</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        
        <!-- total comment list -->
        <comment-list
            :comments="comments"
            :total="total"
            :page="page"
            :pageSize="pageSize"
            :handleCurrentChange="getComments"
        ></comment-list>
        
        <!-- reply list -->
        <el-dialog v-model="showReplyList">
            <el-card shadow="never">
                <template #header style="text-align:left">
                    {{replyTotal}} 条留言
                </template>
                <div>
                    <comment-list
                        :comments="replies"
                        :total="replyTotal"
                        :page="replyPage"
                        :pageSize="replyPageSize"
                        :handleCurrentChange="getReplies"
                        :showBtn="false"
                    ></comment-list>
                </div>
            </el-card>
        </el-dialog>
    </div>
</template>

<script>
import { onMounted, onUnmounted, ref } from 'vue'
import Article from "../components/Article.vue"
import { ElMessage } from 'element-plus'
import { getArticle } from '../api/articles'
import { createComment, getRoots } from '../api/comments.js'
import CommentList from '../components/CommentList.vue'
import bus from '../utils'
export default {
    components: { Article, CommentList },
    props: { id: { type: String } },
    setup(props) {
        const article = ref(null)
        const comments = ref([])
        const pageSize = 5
        const total = ref(0)
        const page = ref(1)
        const showReplyList = ref(false)
        const curTopicId = ref(null)
        const token = ref(null)

        const replies = ref([])
        const replyPageSize = 5
        const replyTotal = ref(0)
        const replyPage = ref(1)

        const getArticleDetail = () => {
            // id是路由传过来时会验证props，但刷新页面不会验证props，这里需要添加一个验证
            if (!props.id.match(/^\d+$/)) {
                ElMessage({
                    showClose: true,
                    message: "id只能是数字",
                    type: "error"
                })
                return
            }
            getArticle(props.id).then(res => {
                article.value = res.data
                console.log("now article", article.value)
                getComments()
            })
        }

        const getComments = (curPage = 1) => {
            getRoots(article.value.id, curPage - 1, pageSize).then(res => {
                comments.value = res.data.items
                total.value = res.data.total
                page.value = curPage
            })
        }

        const getReplies = (curPage = 1) => {
            getRoots(article.value.id, curPage - 1, replyPageSize, curTopicId.value).then(res => {
                replies.value = res.data.items
                replyTotal.value = res.data.total
                replyPage.value = curPage
            })
        }

        const turnPage=(newPage)=>{
            page.value=newPage
            console.log("now page", page.value)
        }

        const turnReplyPage=(newPage)=>{
            replyPage.value=newPage
        }

        onMounted(() => {
            getArticleDetail()
            token.value = localStorage.token
            bus.on("reply", function(val) {
                commentPlaceholder.value = "回复" + val.owner
                form.value.parent_id = val.comment_id
                form.value.topic_id = val.topic_id
                console.log("form", form.value)
                commentDrawer.value = true
            })

            bus.on("showReplyList", (val) => {
                curTopicId.value = val
                getReplies()
                showReplyList.value = true
            })
        })

        onUnmounted(() => {
            bus.off("reply")
            bus.off("showReplyList")
        })

        const formRef = ref(null)

        const form = ref({ owner: "", content: "", parent_id: null, topic_id: null })
        const commentPlaceholder = ref("留言...")
        const rules = {
            owner: [{ required: true, message: "不能为空", trigger: blur }],
            content: [{ required: true, message: "不能为空", trigger: blur }]
        }

        const commentDrawer = ref(false)

        return {
            article, form, formRef, rules, commentDrawer, comments, commentPlaceholder, page, total, pageSize, getComments, showReplyList,
            replies, replyPageSize, replyTotal, replyPage, getReplies,
            turnPage,turnReplyPage, token
        }
    },
    methods: {
        submitComment() {
            this.formRef.validate((valid) => {
                if (valid) {
                    let data = {}
                    for (let i in this.form) {
                        data[i] = this.form[i]
                    }
                    data.article_id = this.id
                    createComment(data).then(res => {
                        if (this.showReplyList) {
                            this.turnReplyPage(1)
                            this.getReplies()
                        } else {
                            this.turnPage(1) 
                            this.getComments()                
                        }
                        this.commentDrawer = false
                    })
                } else {
                    return false
                }
            })
        },
        resetForm() {
            this.formRef.resetFields()
        }
    }
}
</script>

<style>
.drawer-opener {
    position: fixed;
    right: 10%;
    bottom: 20%;
    z-index: 6;
    background-color: rgba(16, 241, 54, 0);
}
.drawer-opener:hover{
    background-color:rgba(131, 245, 150, 0.514);
    border:cyan solid 1px;
    color:cyan;
}
</style>